using System.Collections.Specialized;
using System.Windows;
using System.Windows.Controls;

namespace Xioa_UI.Controls;

public class XioaStepBar : ItemsControl
{
    static XioaStepBar()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(XioaStepBar),
            new FrameworkPropertyMetadata(typeof(XioaStepBar)));
    }

    #region Override方法

    protected override DependencyObject GetContainerForItemOverride()
    {
        return new XioaStepBarItem();
    }

    protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
    {
        //设置Item的显示数字
        XioaStepBarItem stepBarItem = element as XioaStepBarItem;
        ItemsControl itemsControl = ItemsControl.ItemsControlFromItemContainer(stepBarItem);
        int index = itemsControl.ItemContainerGenerator.IndexFromContainer(stepBarItem);
        stepBarItem.Number = System.Convert.ToString(++index);
        base.PrepareContainerForItemOverride(element, item);
    }

    protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
    {
        base.OnItemsChanged(e);

        //ItemsControl数量变化时，重新设置各个Item的显示的数字
        for (int i = 0; i < this.Items.Count; i++)
        {
            XioaStepBarItem stepBarItem = this.ItemContainerGenerator.ContainerFromIndex(i) as XioaStepBarItem;
            
            if (stepBarItem != null)
            {
                int temp = i;
                stepBarItem.Number = System.Convert.ToString(++temp);
            }
        }

        //进度重新回到第一个
        this.Progress = 0;
    }

    #endregion

    public int Progress
    {
        get { return (int)GetValue(ProgressProperty); }
        set { SetValue(ProgressProperty, value); }
    }

    public static readonly DependencyProperty ProgressProperty =
        DependencyProperty.Register("Progress", typeof(int), typeof(XioaStepBar),
            new PropertyMetadata(0, OnProgressChangedCallback, OnProgressCoerceValueCallback));

    private static object OnProgressCoerceValueCallback(DependencyObject d, object baseValue)
    {
        //不让Progress超出边界
        XioaStepBar stepBar = d as XioaStepBar;
        int newValue = System.Convert.ToInt32(baseValue);
        if (newValue < 0)
        {
            return 0;
        }

        if (newValue >= stepBar.Items.Count)
        {
            return stepBar.Items.Count - 1;
        }

        return newValue;
    }

    private static void OnProgressChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
    }
}